package app.hanxiao.com.demo.push.server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.Random;

import app.hanxiao.com.demo.push.Factory.IoListener;
import app.hanxiao.com.demo.push.Factory.MyClientHandler;
import app.hanxiao.com.demo.push.Factory.MyTextLineCodecFactory;


/**
 * 作者：韩笑 on 2017/6/9 0009 10:42
 * <p>
 * 作用：
 */


public class PushServer extends Service {
    private static final String TAG = "PushServer";
    private String DeviceID = "2222"+"\n";
    private String ADDRESS = "";
    private int PORT = 0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG,"服务启动成功 ====> ");
        ADDRESS = intent.getStringExtra("ADDRESS");
        PORT = intent.getIntExtra("PORT",2000);
        //随机生成5位编码
        new MyThread(DeviceID,ADDRESS,PORT).start();
        return super.onStartCommand(intent, flags, startId);
    }

    //启动接收推送线程
    class MyThread extends Thread{
        private String DeviceID = "";
        private String ADDRESS = "";
        private int PORT = 0;
        public MyThread(String DeviceID,String ADDRESS,int PORT){
            this.DeviceID = DeviceID;
            this.ADDRESS = ADDRESS;
            this.PORT = PORT;
        }
        @Override
        public void run() {
            init(DeviceID,ADDRESS,PORT);
        }
    }
    public void init(String DeviceID,String ADDRESS,int PORT) {
        Log.d(TAG,"开始连接后台服务器 ====> ");
        NioSocketConnector connector = new NioSocketConnector();
        connector.setHandler(new MyClientHandler(this));
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MyTextLineCodecFactory()));
        ConnectFuture future = connector.connect(new InetSocketAddress(ADDRESS, PORT));
        future.awaitUninterruptibly();
        Log.d(TAG,"后台服务器连接成功 ====> ");
        IoSession session;
        try {
            session = future.getSession();
        }catch (Exception e){
            return;
        }

        BufferedReader inputReader = null;
        try {
            inputReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(DeviceID.getBytes("utf-8"))));

            String inputContent ;
            while (!(inputContent = inputReader.readLine()).equals("bye")) {
                session.write(inputContent);
                Log.d(TAG,"往服务器发送消息 ====>      " + inputContent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        connector.addListener(new IoListener(connector,DeviceID,ADDRESS,PORT));

    }









    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onDestroy() {
        Intent sevice = new Intent(this, PushServer.class);
        this.startService(sevice);
        super.onDestroy();
    }


    //随机生成唯一编码
    public String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return "XDSCS";
    }
}
